package it.espsoft.easysuperenalotto.logic;

import java.util.HashMap;
import java.util.Map;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

public class RSSHandler extends DefaultHandler{
	private final int stateUnknown = 0;
	private final int stateItem = 1;
	private int state = stateUnknown;
	private String key = "";
	private String[] itemsToExtract = null;
	private Map<String, String> strElements = null;
	
	public RSSHandler(String[] itemsToExtract){
		super();
		this.itemsToExtract = itemsToExtract;
	}
	
	public Map<String, String> getStrElements() {
		return strElements;
	}

	@Override
	public void startDocument() throws SAXException {
		strElements = new HashMap<String,String>();
	}
	
	@Override
	public void endDocument() throws SAXException {
		// TODO Auto-generated method stub
	}
	
	@Override
	public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
		// TODO Auto-generated method stub
		if (localName.equalsIgnoreCase("item")){
			state = stateItem;
		}
	}
	
	@Override
	public void endElement(String uri, String localName, String qName) throws SAXException {
		// TODO Auto-generated method stub
	}
	
	@Override
	public void characters(char[] ch, int start, int length) throws SAXException {
		// TODO Auto-generated method stub
		String strCharacters = new String(ch, start, length);
		
		if (state == stateItem){
			
			for (String item : itemsToExtract) {
				if(strCharacters.toLowerCase().contains(item) ){
					key = item;
				}
			}
			
			if(!"".equals(key)){
				if(strElements.containsKey(key)){
					String tmp = strElements.get(key);
					strElements.remove(key);
					strElements.put(key,tmp+strCharacters.toLowerCase()); 
				}else strElements.put(key, strCharacters.toLowerCase());
			}
		}
	}
}
